<template>
  <div class="app-container" style="height: 100%">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single || ![1,2].includes(selectRow[0].orderDetailStatus) || ![1,6,2].includes(this.orderInfo.orderStatus)"
          @click="handleAllocation"
          v-hasPermi="['outStockOrder:returnGoods:distribute']"
        >{{$t('inOutStock.outStockOrder.allocationBtn')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-view"
          size="mini"
          :disabled="single"
          v-hasPermi="['outStockOrder:returnGoods:pickingTaskOrder']"
          @click.native="getPickingTaskOrder"
        >{{$t('inOutStock.outStockOrder.pickingTaskOrder')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          v-if="selectRow && selectRow[0] && selectRow[0].orderDetailStatus && selectRow[0].orderDetailStatus == 2"
          icon="el-icon-view"
          size="mini"
          :disabled="single"
          v-hasPermi="['outStockOrder:returnGoods:checkAllocation']"
          @click.native="checkAllocation"
        >{{$t('inOutStock.outStockOrder.checkAllocationBtn')}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange"  height="25vh">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column :label="$t('inOutStock.outStockOrder.detailStatus')" align="center" prop="orderDetailStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.out_order_detail_status" :value="scope.row.orderDetailStatus"/>
          <!-- <dict-tag :options="dict.type.picker_task_order_status" :value="scope.row.pickerTaskOrderStatus"/> -->
        </template>
      </el-table-column>
      <af-table-column :label="$t('inOutStock.outStockOrder.productNo')" align="center" prop="productNo" />
      <af-table-column :label="$t('inOutStock.outStockOrder.productName')" align="center" prop="productName" />
      <af-table-column :label="$t('inOutStock.outStockOrder.returnQty')" align="center" prop="orderQty" />
      <af-table-column :label="$t('inOutStock.outStockOrder.pickingQty')" align="center" prop="pickingQty" />
      <af-table-column :label="$t('inOutStock.outStockOrder.unit')" align="center" prop="unit" />
      <af-table-column :label="$t('inOutStock.outStockOrder.returnStorehouseNo')" align="center" prop="returnStorehouseNo" />
      <af-table-column :label="$t('inOutStock.outStockOrder.returnStorehouseName')" align="center" prop="returnStorehouseName" />
      <!-- <af-table-column :label="$t('inOutStock.outStockOrder.pickerName')" align="center" prop="pickerName" />
      <af-table-column :label="$t('inOutStock.outStockOrder.pickerTaskOrderNo')" align="center" prop="pickerTaskOrderNo" />
      <af-table-column :label="$t('inOutStock.outStockOrder.storehouseNo')" align="center" prop="storehouseNo" />
      <af-table-column :label="$t('inOutStock.outStockOrder.storehouseName')" align="center" prop="storehouseName" />
      <af-table-column :label="$t('inOutStock.outStockOrder.locations')" align="center" prop="locations" /> -->
    </el-table>

<!--    <pagination-->
<!--      v-show="total>0"-->
<!--      :total="total"-->
<!--      :page.sync="queryParams.pageNum"-->
<!--      :limit.sync="queryParams.pageSize"-->
<!--      @pagination="getList"-->
<!--    />-->

    <!-- 分配码货员弹窗 -->
    <el-dialog :title="$t('inOutStock.outStockOrder.allocationBtn')" :visible.sync="allocationOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item :label="$t('inOutStock.outStockOrder.productNo')"  prop="productNo">
          <el-input v-model="form.productNo" :disabled="true" :placeholder="$t('inputTip') + $t('inOutStock.outStockOrder.productNo')" />
        </el-form-item>
        <el-form-item :label="$t('inOutStock.outStockOrder.productName')"  prop="productName">
          <el-input v-model="form.productName" :disabled="true" :placeholder="$t('inputTip') + $t('inOutStock.outStockOrder.productName')" />
        </el-form-item>
        <el-form-item label="出库仓库" prop="storehouseNo">
          <el-select @change="changeStorehouse" style="width:100%;" v-model="form.storehouseNo" filterable :placeholder="$t('selectTip') + $t('inOutStock.outStockOrder.storehouseName')">
            <el-option
              v-for="dict in storehouseList"
              :key="dict.no"
              :label="dict.no + '(' + dict.name + ')'"
              :value="dict.no"
              @click.native="form.storehouseName = dict.name"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="出库库区" prop="storehouseAreaNo">
          <el-select @change="changeArea" style="width:100%;" v-model="form.storehouseAreaNo"
                     filterable
                     clearable
                     :placeholder="$t('selectTip') + '出库库区名称'">
            <el-option
              v-for="dict in storehouseAreaList"
              :key="dict.no"
              :label="dict.no + '(' + dict.name + ')'"
              :value="dict.no"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('inOutStock.outStockOrder.pickerName')"  prop="picker">
          <el-select style="width:100%;" v-model="form.picker" filterable :placeholder="$t('selectTip') + $t('inOutStock.outStockOrder.pickerName')">
            <el-option
              v-for="dict in userList"
              :key="dict.userName"
              :label="dict.nickName"
              :value="dict.userName"
              @click.native="form.pickerName = dict.nickName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('inOutStock.outStockOrder.distributeQty')" prop="distributeQty">
          <el-input-number v-model="form.distributeQty" :placeholder="$t('inputTip') + $t('inOutStock.outStockOrder.distributeQty')" :min="1" :precision="0" />
        </el-form-item>
        <el-form-item label="库存可用数量"  prop="usableNum">
          <el-input v-model="form.usableNum" :disabled="true"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="allocationSubmitForm">{{$t('sure')}}</el-button>
        <el-button @click="allocationCancel">{{$t('cancel')}}</el-button>
      </div>
    </el-dialog>

    <!-- 右边抽屉页 拣货单 -->
    <el-drawer
      :title="$t('inOutStock.outStockOrder.pickingTaskOrder')"
      :visible.sync="drawerShow"
      direction="rtl"
      :before-close="handleClose"
      size="50%">
      <el-table :data="pickingTaskOrder">
        <af-table-column align="center" property="no" width="154" :label="$t('inOutStock.outStockOrder.no')"/>
        <af-table-column align="center" property="status" :label="$t('inOutStock.outStockOrder.status')">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.picker_task_order_status" :value="scope.row.status"/>
          </template>
        </af-table-column>
        <af-table-column align="center" property="locations" width="150" :label="$t('inOutStock.outStockOrder.locations')"/>
        <af-table-column align="center" property="storehouseNo" width="120" :label="$t('inOutStock.outStockOrder.storehouseNo')"/>
        <af-table-column align="center" property="distributeQty" :label="$t('inOutStock.outStockOrder.distributeQty')"/>
        <af-table-column align="center" property="pickingQty" :label="$t('inOutStock.outStockOrder.pickingQty')"/>
        <af-table-column align="center" property="pickerName" :label="$t('inOutStock.outStockOrder.pickerName')"/>
        <af-table-column align="center" property="qualityTaskNo" :label="$t('inOutStock.outStockOrder.qualityTaskNo')"/>
        <af-table-column align="center" property="type" :label="$t('inOutStock.outStockOrder.taskType')">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.out_stock_order_type" :value="scope.row.type"/>
          </template>
        </af-table-column>
        <af-table-column align="center" property="productNo" width="106" :label="$t('inOutStock.outStockOrder.productNo')"/>
        <af-table-column align="center" property="productName" width="110" :label="$t('inOutStock.outStockOrder.productName')"/>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="90px" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="getPickingRecords(scope.row)"
              :disabled="scope.row.status == '1' || scope.row.status == '4'"
              >拣货记录</el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDeletePickingTask(scope.row)"
              :disabled="scope.row.status != '4'"
              >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>


    <!-- 拣货记录 -->
    <el-dialog
      :title="$t('inOutStock.outStockOrder.pickingRecord')"
      :visible.sync="pickingRecodeVisible"
      width="800px" append-to-body>
      <el-table :data="pickingRecords">
        <af-table-column align="center" property="barcode" width="154" :label="$t('inOutStock.outStockOrder.barcode')"/>
        <af-table-column align="center" property="pickingQty" :label="$t('inOutStock.outStockOrder.recordPickingQty')"/>
        <af-table-column align="center" property="storehouseLocationNo" :label="$t('inOutStock.outStockOrder.storehouseLocationNo')"/>
      </el-table>
    </el-dialog>


    <!-- 添加或修改出库申请单明细对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item :label="$t('inOutStock.outStockOrder.product')" prop="productNo">
          <el-select style="width:100%;" v-model="form.productNo" filterable :placeholder="$t('selectTip') + $t('inOutStock.outStockOrder.product')">
            <el-option
              v-for="dict in productList"
              :key="dict.productNo"
              :label="dict.productName"
              :value="dict.productNo"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('inOutStock.outStockOrder.orderQty')" prop="orderQty">
          <el-input-number v-model="form.orderQty" :placeholder="$t('inputTip') + $t('inOutStock.outStockOrder.orderQty')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('sure')}}</el-button>
        <el-button @click="cancel">{{$t('cancel')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { listOrder, getOrder, delOrder, addOrder, updateOrder, distributePickerTask,pickerTaskOrderByOutOrderId, delPickerTaskOrder, pickingRecordList, checkPicker,getStorehouseAreaPicker } from "@/api/inOutStock/outStockDetailOrder";
  import { listStorehouse,getStorehouseListByProductNo,getAvailableQty } from "@/api/basic/storehouse";
  import { listUser } from "@/api/system/user";
  import { listArea } from "@/api/basic/area";
  import { listProduct } from "@/api/basic/product";

  export default {
    name: "Order",
    dicts: ['out_order_detail_status', 'out_stock_order_type', 'picker_task_order_status'],
    props:{
      orderData:{}
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        selectRow: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 出库单明细表格数据
        orderList: [],
        // 仓库列表
        storehouseList: [],
        storehouseAreaList: [],
        // 用户列表
        userList: [],
        oldUserList: [],
        // 物料列表
        productList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示分配码货员弹出层
        allocationOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          no: null,
          orderNo: null,
          productNo: null,
          orderDetailStatus: null,
          orderQty: null,
          actualQty: null,
          sort: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          picker: [
            { required: true, message: this.$t('inOutStock.outStockOrder.pickerName') + this.$t('notEmpty'), trigger: "change" }
          ],
          storehouseNo: [
            { required: true, message: this.$t('inOutStock.outStockOrder.storehouseName') + this.$t('notEmpty'), trigger: "change" }
          ],
          distributeQty: [
            { required: true, message: this.$t('inOutStock.outStockOrder.distributeQty') + this.$t('notEmpty'), trigger: "change" }
          ],
          orderQty: [
            { required: true, message: this.$t('inOutStock.outStockOrder.orderQty') + this.$t('notEmpty'), trigger: "blur" },
            {
              validator: (rule, value, callback) => {
                if (value < 1) {
                  callback(new Error(this.$t('inOutStock.outStockOrder.orderQtyCheckMsg')));
                } else {
                  callback()
                }
              },
              trigger: "change",
            },
          ],
          productNo: [
            { required: true, message: this.$t('inOutStock.outStockOrder.product') + this.$t('notEmpty'), trigger: "change" }
          ],
        },
        // 订单信息
        orderInfo:{
          no : null,
          orderType : null
        },
        //抽屉页是否展示
        drawerShow: false,
        // 拣货记录弹窗
        pickingRecodeVisible: false,
        //拣货单列表
        pickingTaskOrder: [],
        //拣货记录列表
        pickingRecords: [],
        //详情行选择
        detailSelect: {},
      };
    },
    created() {
      this.getList();
      this.getStorehouseList();
      this.getUserList();
      this.getProductList();
    },
    watch: {
      // 监视订单信息变动
      orderData(newValue){
        if(!newValue || !newValue.no){
          this.orderInfo = {no : null};
        }else {
          this.orderInfo = newValue;
        }
        this.detailSelect = {};
        this.getList();
      }
    },
    methods: {
      // 查询库存可用数量
      getAvailableQty(){
        getAvailableQty({
          storehouseNo:this.form.storehouseNo,
          areaNo:this.form.storehouseAreaNo || '',
          detailId:this.form.id,
        }).then(response => {
          this.$set(this.form,'usableNum',response.data);
        });
      },
      // 库区变更
      changeArea(row){
        // 先将码货员列表改为原先的数据
        this.$set(this,'userList',this.oldUserList);
        // 查询库区对应的拣货员
        getStorehouseAreaPicker({
          storehouseArea:row,
          pageSize: 0
        }).then(response => {
          if (response.code == 200 && response.total > 0){
            response.rows.forEach((item) => {
              item.userName = item.shipper;
              item.nickName = item.shipperName;
            });
            this.$set(this,'userList',response.rows);
          }
        });
        this.getAvailableQty()
      },
      /** 查询出库单明细列表 */
      getList() {
        this.loading = true;

        this.queryParams.orderNo = this.orderInfo.no;
        if(!this.queryParams.orderNo){
          this.orderList = [];
          this.total = 0;
          this.loading = false;
          return;
        }

        listOrder({...this.queryParams,pageSize: 0}).then(response => {
          this.orderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 获取用户列表
      getUserList(){
        listUser({pageSize:0,status:0}).then(response => {
          this.userList = response.rows;
          this.oldUserList = response.rows;
        });
      },
      // 获取物料列表
      getProductList(){
        listProduct({pageSize:0,status:0}).then(response => {
          this.productList = response.rows;
        });
      },
      // 获取仓库列表
      getStorehouseList(){
        listStorehouse({pageSize: 0}).then(response => {
          this.storehouseList = response.rows;
        });
      },
      // 分配拣货员弹窗仓库列表（根据物料编号查询）
      getStorehouseListByProductNo(productNo){
        getStorehouseListByProductNo(productNo).then(response => {
          this.storehouseList = response.data;
        });
      },
      // 仓库变更
      changeStorehouse(row){
        this.form.storehouseName = row.name;
        this.$set(this.form,'storehouseAreaNo','');
        this.$set(this.form,'picker','');
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
        // 查询仓库下的库位
        listArea({
          storehouseNo:this.form.storehouseNo,
          whetherMp:'N',
          pageSize:0,
        }).then(response => {
          this.$set(this,'storehouseAreaList',response.rows);
        });
        // 查询库存可用数量
        this.getAvailableQty()
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 分配码货员取消按钮
      allocationCancel() {
        this.allocationOpen = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          no: null,
          orderNo: null,
          productNo: null,
          storehouseNo: null,
          distributeQty: null,
          storehouseName: null,
          orderDetailStatus: 0,
          orderQty: 0,
          actualQty: null,
          sort: null,
          remark: null,
          picker: null,
          pickerTaskOrderNo: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.selectRow = selection.map(item => item);
        this.single = selection.length!==1;
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = this.$t('inOutStock.outStockOrder.addDetail');
      },
      /** 修改按钮操作 */
      handleUpdate() {
        let row = null;
        this.orderList.forEach((item) => {
          if(item.id == this.ids[0]){
            row = item;
          }
        });
        if(!row || row.pickerTaskOrderNo){
          this.$modal.msgError(this.$t('inOutStock.outStockOrder.allocationBtnCheckMsg'));
          return;
        }
        this.reset();
        const id = row.id || this.ids;
        getOrder(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = this.$t('inOutStock.outStockOrder.editDetail');
        });
      },
      /** 分配拣货员按钮操作 */
      handleAllocation(row) {
        this.reset();
        const id = row.id || this.ids;
        getOrder(id).then(response => {
          this.form = response.data;
          this.getStorehouseListByProductNo(this.form.productNo)
          if(this.orderInfo.returnType === 1){
            this.form.storehouseNo = this.form.returnStorehouseNo;
            this.form.storehouseName = this.form.returnStorehouseName;
          }
          this.allocationOpen = true;
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.orderNo = this.orderInfo.no;
            if (this.form.id != null) {
              updateOrder(this.form).then(response => {
                this.$modal.msgSuccess(this.$t('editSuc'));
                this.open = false;
                this.getList();
              });
            } else {
              addOrder(this.form).then(response => {
                this.$modal.msgSuccess(this.$t('addSuc'));
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 分配码货员提交按钮 */
      allocationSubmitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            distributePickerTask(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('operateSuc'));
              this.allocationOpen = false;
              this.getList();
            });
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
          return delOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('deleteSuc'));
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('inOutStock/outStockDetailOrder/export', {
          ...this.queryParams
        }, `order_${new Date().getTime()}.xlsx`)
      },
      // 抽屉页面关闭
      handleClose(done) {
        done();
        // this.$confirm('确认关闭？')
        //   .then(_ => {
        //     done();
        //   })
        //   .catch(_ => {});
      },
      /** 根据单据编号获取拣货单 */
      getPickingTaskOrder(){
        if(!this.ids[0]){
          this.pickingTaskOrder = [];
          this.drawerShow = true;
          return;
        }
        pickerTaskOrderByOutOrderId(this.ids[0]).then(response => {
          this.pickingTaskOrder = response.data;
          this.drawerShow = true;
        });
      },
      // 删除拣货单
      handleDeletePickingTask(row) {
        const ids = row.id;
        this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
          return delPickerTaskOrder(ids);
        }).then(() => {
          this.$modal.msgSuccess(this.$t('deleteSuc'));
          this.getPickingTaskOrder();
        }).catch(() => {});
      },
      // 根据拣货单获取拣货记录
      getPickingRecords(row){
        pickingRecordList({orderDetailNo: row.no, pageSize:0}).then(response => {
          this.pickingRecords = response.rows;
          this.pickingRecodeVisible = true;
        });
      },
      // 确认分配 按钮
      checkAllocation(){
        let that = this
        this.$modal.confirm('是否确认分配？').then(function() {
          return checkPicker(that.selectRow[0].id)
        }).then(() => {
          this.getList();
        })
      },
      // 是否可以分配或编辑判断
      // isAllocationAndEdit(){
      //   return this.single || ![1,2].includes(this.orderInfo.orderStatus)
      //     || !this.selectRow[0] || this.selectRow[0].pickingQty > 0;
      // },
    }
  };
</script>
